// TCPClient project main.go
package monitor

import (
    //"bytes"
    //"fmt"
)

type tsHead struct {
	sync		uint8
	pid			uint16
	order 		uint8
	tableId 	uint8
	sectionLen 	uint16
	checkByte 	uint8
	cnt 		uint8
	cmdType 	uint8
	cmdBit 		uint8
	cmdLv 		uint8
	logicAddr	[]byte
	swSta		uint8
	emFlag		uint8
	volCH		uint8
	pgId		uint16
}


const (
	pgCmdHold  = 0
	pgCmdPlay  = 1
	pgCmdStop  = 2
	pgCmdDrill = 3
)
const (
	playWcntMax int = 16
	cmdWcntMax int = 60
)

func lenthLogicId(id []byte) int {
	var i int
	var n byte
	for i, n = range id {
		if n == 0xff {
			break
		}
	}
	return i
}


func search_pg(data []byte, pg *PgInfo) {
	const (
		none = 0
		update = 1
		hold = 2
	)
	var ret int = none 
	swSta := data[7] >> 6
	pgId := (uint16(data[8]) << 0x8 | uint16(data[9]))

	switch swSta {
	case pgCmdStop:
		if pg.swSta != pgCmdStop && pgId == pg.pgId{
			pg.CmdStop()
		}
	default:
		emFlag := (data[7] >> 5)&0x1
		cmdLv := data[0] >> 3
		logicAddr := data[1:7]
		if emFlag < pg.emFlag || cmdLv < pg.cmdLv {
			break
		}
		if pg.swSta == pgCmdStop {
			IdbgPg(3, "new pg 1st one")
			ret = update 
		}
		if emFlag > pg.emFlag {
			IdbgPg(3, "new pg higher emFlag")
			ret = update 
		}else if cmdLv > pg.cmdLv {
			IdbgPg(3, "new pg higher cmdLv")
			ret = update 
		}else if lenthLogicId(logicAddr[:]) < lenthLogicId(pg.logicAddr[:6]) {
			IdbgPg(3, "new pg shorter logicID")
			ret = update 
		}else if pgId == pg.pgId {
			IdbgPg(3, "pg hold")
			ret = hold 
		}
		
		if ret > none{
			pg.playwcnt	= playWcntMax
			if ret == update {
				pg.cmdLv 	= cmdLv		
				pg.swSta	= swSta
				pg.emFlag	= emFlag
				pg.pgId		= pgId
				copy(pg.logicAddr[:6], logicAddr)
				IdbgPg(2, "PG更新", pg.Pginfo())			
			}
		}
	}
}

func parse_tsType(data []byte, cmdPid uint16) int {
	var ret int = 0
	var pid uint16 = (uint16(data[1]) << 0x8 | uint16(data[2]))&0x1fff
	
	if pid != cmdPid {
		return 0
	}
	cnt := data[9]
	cmdType := data[10] >> 6

	
	switch cmdType{
		case 0:
			if(cnt == 0 && data[10] == 0) {
				ret= 0
			}else {
				ret= 1
			}
		case 1:
		case 2:
		case 3:
			ret= 0
			
	}
	return ret
}

func TsParse(data []byte, cmdpid uint16, pg *PgInfo) {
	var pts tsHead
	n := len(data)
	
	if 0 == parse_tsType(data, cmdpid){
		return
	}
	IdbgCmdHex(3, data)
	pts.sync = data[0]
	pts.pid = (uint16(data[1]) << 0x8 | uint16(data[2]))&0x1fff
	pts.order = data[3] >> 4
	pts.tableId = data[5]
	pts.sectionLen = (uint16(data[6]) << 0x8 | uint16(data[7]))&0x0FFF
	pts.checkByte= data[8]
	pts.cnt= data[9]
	pts.cmdType= data[10] >> 6
	pts.cmdBit= (data[10] >> 3 ) &0x7
	pts.cmdLv= data[10]&0x7
	pts.logicAddr= data[11:17]

	var cnt int = int(pts.cnt)
	var rlen int = int(pts.sectionLen)
	if(rlen + 10 < n){
		rlen= n- 10
	}
	idx := 10
	for cnt > 0 && rlen > 10 {
		search_pg(data[idx: idx+10], pg)
		cnt--
		rlen-= 10
		idx+= 10
	}
}







